package com.dbky.alg.browser;

import com.dbky.alg.browser.support.SimpleResponse;
import com.dbky.alg.core.properties.AlgSecurityProperties;
import com.dbky.alg.core.properties.LoginType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: tianchao
 * @Date: 2020/6/25 00:24
 * @Description:
 */
//implements AuthenticationSuccessHandler
public class CustomerAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private Logger logger = LoggerFactory.getLogger(CustomerAuthenticationSuccessHandler.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AlgSecurityProperties securityProperties;
    /**
     * Called when a user has been successfully authenticated.
     *
     * @param request        the request which caused the successful authentication
     * @param response       the response
     * @param authentication the <tt>Authentication</tt> object which was created during
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        logger.info("登录成功...");
        if (LoginType.JSON==securityProperties.getBrowser().getLoginType()){
            logger.info(authentication.getClass() + " ---> "+authentication);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse("登录成功。。。")));
        }else{
            super.onAuthenticationSuccess(request, response, authentication);
        }

    }
}
